//
//  LocationManager.m
//  Sydney
//
//  Created by 张超 on 2018/4/9.
//  Copyright © 2018年 chinajci. All rights reserved.
//
#import "FlutterLocationPlugin.h"
#import "LocationManager.h"

@interface LocationManager ()
@property (nonatomic, strong) NSMutableArray* resultArray;
//@property (nonatomic,copy) LocationResultBlock resultBlock;
@property (assign, nonatomic) BOOL locationWanted;
@end

@implementation LocationManager

+ (instancetype)shareLocationManager
{
    static LocationManager *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _sharedManager = [[LocationManager alloc] init];
    });
    
    return _sharedManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        manager =  [[CLLocationManager alloc] init];
        [manager requestWhenInUseAuthorization];
        [manager requestAlwaysAuthorization];//iOS8必须，这两行必须有一行执行，否则无法获取位置信息，和定位
        // 设置代理
        manager.delegate = self;
        // 设置定位精确度到米
        manager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        manager.distanceFilter = kCLDistanceFilterNone;
        self.resultArray = [[NSMutableArray alloc] init];
        geocoder = [[CLGeocoder alloc] init];
    }
    return self;
}

- (void)reusltInfo:(NSDictionary*)info {
    [self.resultArray enumerateObjectsUsingBlock:^(FlutterResult  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj(info);
        [self.resultArray removeObject:obj];
    }];
}

- (void)startUpdatingLocation:(id) result{
    [self.resultArray addObject:result];
    self.locationWanted = YES;
    if ([self isPermissionGranted]) {
        [manager startUpdatingLocation];
    } else {
        [self requestPermission];
        if ([self isPermissionGranted]) {
            [manager startUpdatingLocation];
        }
        else {
            self.locationWanted = NO;
            NSDictionary* resultInfo = [@{@"error":@"获取位置失败"} copy];
            [self reusltInfo:resultInfo];
        }
    }
}

- (void)stopUpdatingLocation
{
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    NSLog(@"%lu",(unsigned long)locations.count);
    CLLocation * location = locations.lastObject;
    // 纬度
    CLLocationDegrees latitude = location.coordinate.latitude;
    // 经度
    CLLocationDegrees longitude = location.coordinate.longitude;
    NSLog(@"lng:%1f,lat:%1f",longitude,latitude);
    NSMutableDictionary* resultInfo = [[NSMutableDictionary alloc] init];
    [resultInfo setObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];
    [resultInfo setObject:[NSNumber numberWithDouble:longitude] forKey:@"longitude"];
    [resultInfo setObject:[self getFormatTime:[NSDate date]] forKey:@"callbackTime"];

    __weak typeof(self) wself = self;
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        __strong typeof(self) _self = wself;
     
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            if (city.length)
                [resultInfo setObject:city forKey:@"city"];
            if (placemark.country.length)
                [resultInfo setObject:placemark.country forKey:@"country"];
            if (placemark.subLocality.length)
                [resultInfo setObject:placemark.subLocality forKey:@"district"];
            if (_self.locationWanted) {
                _self.locationWanted = NO;
                 [_self reusltInfo:resultInfo];
            }
        }else if (error == nil && [placemarks count] == 0) {
            if (_self.locationWanted) {
                _self.locationWanted = NO;
                [_self reusltInfo:resultInfo];
            }
        } else if (error != nil){
            if (_self.locationWanted) {
                _self.locationWanted = NO;
               [_self reusltInfo:resultInfo];
            }
        }
    }];
    [self stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if(self.locationWanted)
    {
        self.locationWanted = NO;
        NSDictionary* resultInfo = [@{@"error":@"获取位置失败"} copy];
        [self reusltInfo:resultInfo];
    }
}

- (NSString *)getFormatTime:(NSDate*)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *timeString = [formatter stringFromDate:date];
    return timeString;
}

-(BOOL) isPermissionGranted {
    BOOL isPermissionGranted = NO;
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
#if TARGET_OS_OSX
    if (status == kCLAuthorizationStatusAuthorized) {
        // Location services are available
        isPermissionGranted = YES;
    } else if (@available(macOS 10.12, *)) {
        if (status == kCLAuthorizationStatusAuthorizedAlways) {
            // Location services are available
            isPermissionGranted = YES;
        }
    }
#else //if TARGET_OS_IOS
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
       status == kCLAuthorizationStatusAuthorizedAlways) {
        // Location services are available
        isPermissionGranted = YES;
    }
#endif
    else if (status == kCLAuthorizationStatusDenied ||
       status == kCLAuthorizationStatusRestricted) {
        // Location services are requested but user has denied / the app is restricted from
        // getting location
        isPermissionGranted = NO;
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        // Location services never requested / the user still haven't decide
        isPermissionGranted = NO;
    } else {
        isPermissionGranted = NO;
    }
    
    return isPermissionGranted;
}


-(void) requestPermission {
#if TARGET_OS_OSX
    if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil) {
        if (@available(macOS 10.15, *)) {
            [manager requestAlwaysAuthorization];
        }
    }
#else
    if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"] != nil) {
        [manager requestWhenInUseAuthorization];
    }
    else if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"] != nil) {
        [manager requestAlwaysAuthorization];
    }
#endif
    else {
        [NSException raise:NSInternalInconsistencyException format:
            @"To use location in iOS8 and above you need to define either "
            "NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in the app "
            "bundle's Info.plist file"];
    }
}

@end
